function countOfAtoms(formula: string): string {
    function countAtoms(f: string): Map<string,number> {
        let atoms: Map<string, number> = new Map();
        let i: number=0;
        while(i<f.length){
            if(f[i].charCodeAt(0)>='A'.charCodeAt(0) && f[i].charCodeAt(0)<='Z'.charCodeAt(0)){
                let s = i;
                i++;
                while(i<f.length && f[i] !=='(' && f[i].charCodeAt(0)>='a'.charCodeAt(0) && f[i].charCodeAt(0)<='z'.charCodeAt(0)){
                    i++;
                }
                let key = f.substr(s, i-s);
                let c = i;
                while(i<f.length && f[i].charCodeAt(0)>='0'.charCodeAt(0) && f[i].charCodeAt(0)<='9'.charCodeAt(0)){
                    i++;
                }
                let freq: number = c === i ? 1 : parseInt(f.substr(c,i-c));
                if(atoms.has(key)){
                    atoms.set(key,atoms.get(key) + freq);
                }
                else{
                    atoms.set(key,freq);
                }
            }
            else{
                let bra = i;
                let bs: number = 1;
                i++;
                while(bs!==0){
                    if(f[i]==='('){
                        bs++;
                    }
                    if(f[i]===')'){
                        bs--;
                    }
                    i++;
                }
                let subAtom = countAtoms(f.substr(bra+1,i-bra-2));
                let co = i;
                while(i<f.length && f[i].charCodeAt(0)>='0'.charCodeAt(0) && f[i].charCodeAt(0)<='9'.charCodeAt(0)){
                    i++;
                }
                let freq: number = co === i ? 1 : parseInt(f.substr(co,i-co));
                for(let k of subAtom.keys()){
                    if(atoms.has(k)){
                        atoms.set(k,atoms.get(k) + subAtom.get(k) * (freq || 1));
                    }
                    else{
                        atoms.set(k,subAtom.get(k) * (freq || 1));
                    }
                }           
            }
        }
        return atoms;
    }
    let map = countAtoms(formula);
    let ret: string = Array.from(map.keys()).sort().map( e => map.get(e) === 1 ? e:e+map.get(e).toString()).join('');
    return ret;
};

// 执行用时：
// 128 ms
// , 在所有 TypeScript 提交中击败了
// 100.00%
// 的用户
// 内存消耗：
// 45.5 MB
// , 在所有 TypeScript 提交中击败了
// 100.00%
// 的用户